(function( $ ){
    
    var defaults = {
        'load': function(){},
        'scrollTarget': null,
        //it can be int px or auto, default auto
        'heightOffset': 'auto'
    };
    
    var loadContent = function(obj, opts){
        var target = $(opts.scrollTarget);
        if(0 != $(obj).scrollTop())
        {
            if((0 < $(obj).length && (obj === window || $(obj).is(':visible'))) && location.href == opts.url)
            {
                var mayLoadContent = false;
                if('auto' === opts.heightOffset || opts.heightOffset >= $(obj).height())
                    mayLoadContent = ($(obj).scrollTop() + $(obj).height()) / target.height() >= 0.7;
                else
                    mayLoadContent = $(obj).scrollTop() + opts.heightOffset + $(obj).height() >= target.height();

                if (mayLoadContent)
                    opts.load();
            }    
            else
                $(obj).stopScrollPagination();
        }
    };
    
    $.fn.scrollPagination = function(opts) {
        var options = $.extend({}, defaults, opts, {
            url: location.href
        });  
        if( ! options.scrollTarget)
        {
            console.error('the scrollTarget is missing');
            return false;
        }
        
        $(this).unbind('scroll');
        $(this).attr('scrollPagination', 'enabled');
        $(this).scroll(function(event){
            if ($(this).attr('scrollPagination') == 'enabled')
                loadContent(this, options);		
            else
                event.stopPropagation();	
        });
        
        return $(this);
    };

    $.fn.stopScrollPagination = function(){
        return $(this).attr('scrollPagination', 'disabled');
    };
  
})( jQuery );